<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 16/8/12
 * Time: 19:37
 */

namespace app\admin\controller;


use app\admin\services\MenuService;
use app\admin\services\WeixinMenuService;
use app\common\controller\Base;
use app\common\util\CUrl;
use app\common\util\weixin\AccessToken;
use app\common\util\weixin\OAuth;
use app\common\util\weixin\WxApi;

class Weixin extends Base
{
    /**
     * @var WeixinMenuService
     */
    protected $_service;
    private $menus;

    protected function _setService()
    {
        $this->menus =[
            'default' => [
                'appid' => C('weixin.ccnn_appid'),
                'appsecret' => C('weixin.ccnn_appsecret'),
                'text'=>'默认',
            ],
        ];
        $this->_service = new WeixinMenuService();
    }

    public function find($page = 1, $rows = 10, $sort = 'id', $order = 'desc')
    {
        return parent::pagination($page, $rows, $sort, $order);
    }

    public function menu()
    {
        return $this->fetch();
    }

    public function saveEntry()
    {
        return parent::saveModel();
    }

    public function getMenusByPId($pid = 0, $root = 0)
    {
        $menuServices = new MenuService();
        $rt = $menuServices->getMenusByParentId($pid, 'weixin_menu');
        if ($root) {
            array_unshift($rt, array(
                'id' => 0,
                'text' => 'Root'
            ));
        }
        return $this->returnJSON($rt);
    }


    public function getMenusByParentId()
    {
        $db = M('weixin_menu');
        $menus = $db->field('is_auth,id,title as name,url,parent_id,type,key,media_id')->where(array('is_valid' => 1))->order('sort desc,id asc')->select();
        $temp = array();
        $_pid = 0;
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1f82009650462236&redirect_uri=http://carsystem.juluck.com/index.php/Home/MerchantPayee/index.html&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirectA
        foreach ($menus as $m) {
            $pid = $m['parent_id'];
            $id = $m['id'];
            if ($m['url'] && strpos($m['url'], '://') === false) {
                $m['url'] = U($m['url']);
            }
            if ($m['is_auth'] == 1) {
                $m['url'] = sprintf(
                    'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect',
                    AccessToken::getAppId(),
                    urlencode($m['url'])
                );
            }
            if (isset($temp[$id])) {
                $m['sub_button'] = $temp[$id]['sub_button'];
            }
            foreach (array('type', 'key', 'url', 'media_id', 'is_auth') as $v) {
                if (empty($m[$v])) {
                    unset($m[$v]);
                }
            }
            $temp[$id] = $m;
            if ($pid > 0 && $pid != $id) {
                if (!isset($temp[$pid])) {
                    $temp[$pid] = array();
                }
                if (!isset($temp[$pid]['sub_button'])) {
                    $temp[$pid]['sub_button'] = array();
                }
                $temp[$pid]['sub_button'][] = &$temp[$id];
            }
        }
        $_temp = array();
        foreach ($temp as $key => &$m) {
            if ($m['parent_id'] != $_pid || $m['parent_id'] == $m['id']) {
                unset($m['id']);
                unset($m['parent_id']);
                unset($temp[$key]);
            } else {
                unset($m['id']);
                unset($m['parent_id']);
                $_temp[] = $m;
            }
        }
        return $_temp;
    }

    private function api_notice_increment($url, $data)
    {
        $ch = curl_init();
        $header = array('Accept-Charset' => 'utf-8');
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        //     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        curl_close($ch);
        return $tmpInfo;
    }

    public function downMenu()
    {
        $type = I('get.type', '', 'trim');
        if (!empty($this->menus[$type])) {
            $config = $this->menus[$type];
            AccessToken::config($config['appid'], $config['appsecret']);
            $url = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=' . AccessToken::getAccessToken();
            return json_encode(json_decode(CUrl::httpGet($url), true), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }
        return '';
    }

    public function submitMenu()
    {
        WxApi::init();
        $rt = $this->getMenusByParentId();
        $content = json_encode(array(
            'button' => $rt
        ), JSON_UNESCAPED_UNICODE);
        $token = AccessToken::getAccessToken();
        $create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $token;
        $response = $this->api_notice_increment($create_menu_url, $content);
        $m = json_decode($response, true);
        if ($m['errcode'] == 0) {
            return $this->jsonSuccess("修改成功");
        } else {
            return $this->jsonFail("错误码: " . $m['errcode'] . " 内容:" . $m['errmsg']);
        }
    }


    public function submitMenu2()
    {
        $type = I('post.type', '', 'trim');
        $menus = I('post.menus', '', 'trim');
        if (!empty( $this->menus[$type]) && !empty($menus)) {
            try{
                $menus = json_decode($menus, true);

                $content = json_encode(array(
                    'button' => $menus['menu']['button']
                ), JSON_UNESCAPED_UNICODE);
                $config =  $this->menus[$type];
                AccessToken::config($config['appid'], $config['appsecret']);
                $token = AccessToken::getAccessToken();
                $create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $token;
                $response = $this->api_notice_increment($create_menu_url, $content);

                $m = json_decode($response, true);
                if ($m['errcode'] == 0) {
                    return $this->jsonSuccess("修改成功");
                } else {
                    return $this->jsonFail("错误码: " . $m['errcode'] . " 内容:" . $m['errmsg']);
                }
            }catch(\Exception $ex){
                return $this->jsonFail($ex->getMessage());
            }
        }
    }




    public function index2()
    {

        $this->assign('wxlist',$this->menus);
        return $this->fetch();
    }


}